package model

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"gorm.io/gorm"
	"time"
)

type (
	UserProjectModel interface {
		Insert(user User) (err error)
		PdOne(user User) bool
		FindOne(user User) (User, error)
		GetId(user User) (int, error)
	}

	DefaultUserProjectModel struct {
		conn  *gorm.DB
		table string
	}

	User struct {
		User_id       int       `db:"user_id"  json:"user_id"`
		User_Account  string    `db:"user_account"  json:"user_account"`
		User_Password string    `db:"user_password" json:"user_password"`
		Create_time   time.Time `db:"create_time"  json:"create_time"`
		Delete_time   time.Time `db:"delete_time"  json:"delete_time"`
		DelState      int       `db:"del_state"  json:"del_state"`
	}
)

func NewDefaultUserProjectModel(conn *gorm.DB) *DefaultUserProjectModel {
	return &DefaultUserProjectModel{
		conn:  conn,
		table: "user",
	}
}

func (u *DefaultUserProjectModel) Insert(user User) (err error) {
	user.Create_time = time.Now()
	user.Delete_time = time.Unix(0, 0)
	hasher := md5.New()
	hasher.Write([]byte(user.User_Password))
	hashedPassword := hasher.Sum(nil)
	user.User_Password = hex.EncodeToString(hashedPassword)
	u.conn.Create(&user)
	return err
}

func (u *DefaultUserProjectModel) GetId(user User) (int, error) {
	us1, err := u.FindOne(user)
	if err != nil {
		return -1, err
	}
	return us1.User_id, err
}
func (u *DefaultUserProjectModel) PdOne(user User) bool {
	var count int64
	u.conn.Model(&user).Where("user_account=?", user.User_Account).Count(&count)
	if count <= 0 {
		return false
	}
	return true
}
func (u *DefaultUserProjectModel) FindOne(user User) (User, error) {
	var err error
	var count int64
	u.conn.Model(&user).Where("user_account=?", user.User_Account).Count(&count)
	if count <= 0 {
		err = errors.New("数据不存在")
		return User{}, err
	}
	u.conn.Where("user_account=?", user.User_Account).First(&user)

	return user, nil
}
